package response

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"gitee.com/youkelike/ziam/zsdk/sdk/errors"
)

type Response interface {
	ParseErrorFromHTTPResponse(body []byte) error
}

type ErrorResponse struct {
	Code      int    `json:"code"`
	Message   string `json:"message,omitempty"`
	RequestID string `json:"requestID,omitempty"`
}

type BaseResponse struct {
	ErrorResponse
	Body []byte
}

func (r *BaseResponse) ParseErrorFromHTTPResponse(body []byte) error {
	if err := json.Unmarshal(body, r); err != nil {
		return err
	}
	if r.Code > 0 {
		return errors.NewMEDUSDKError(r.Code, r.Message, r.RequestID)
	}
	r.Body = body

	return nil
}

func ParseFromHttpResponse(rawResp *http.Response, resp Response) error {
	defer rawResp.Body.Close()

	body, err := io.ReadAll(rawResp.Body)
	if err != nil {
		return err
	}
	// 如果用 rawResp.Status 来判断，会比较麻烦
	if rawResp.StatusCode != 200 {
		return fmt.Errorf("request fail with status: %s, with body: %s", rawResp.Status, body)
	}

	if err := resp.ParseErrorFromHTTPResponse(body); err != nil {
		return err
	}

	return nil
	// return json.Unmarshal(body, &resp)
}
